# Flask表单
# pip install flask_wtf

from flask import Flask,request,render_template
from flask_wtf import FlaskForm
from wtforms import StringField,PasswordField,IntegerField,RadioField,SubmitField  # 表单控件数据类型模块
from wtforms.validators import DataRequired,EqualTo,Length,NumberRange # 验证数据不能为空的模块

app = Flask(__name__)
app.config["SECRET_KEY"] = "ABCDEFG"

# 定义表单模型类
class Register(FlaskForm):
    user_name = StringField(label="用户名",validators=[DataRequired("用户名不能为空"),Length(min=3,max=8,message="用户名长度不匹配")])
    password = PasswordField(label="密码",validators=[DataRequired("密码不能为空")])
    password2 = PasswordField(label="确认密码", validators=[DataRequired("密码不能为空"),EqualTo("password",message="两次密码不相等")])
    age = IntegerField(label="年龄",validators=[DataRequired("年龄不能为空"),NumberRange(min=0,max=100,message="年龄不能为负数")])
    gender = RadioField(label="性别",choices=[("gender1","男"),("gender0","女")])
    address = StringField(label="地址",validators=[DataRequired("地址不能为空")])
    submit = SubmitField(label="立即注册")

# 注册
@app.route("/register",methods=["GET","POST"])
def register():
    # 创建表单对象
    form = Register()
    if request.method == "GET":
        return render_template("register2.html",form=form)
    if request.method == "POST":
        # 进行数据验证
        # validate_on_submit() 是一个表单验证器,表单传递过来数据如果都正确则执行
        if form.validate_on_submit():
            username = form.user_name.data
            password = form.password.data
            password2 = form.password2.data
            age = form.age.data
            gender = form.gender.data
            address = form.address.data

            print(username,password,password2,age,gender,address)
        else:
            print("验证失败")
            return render_template("register2.html",form=form)

        return "数据接收成功"



if __name__ == '__main__':
    app.run()